#include "Buzzer.h"

static void GPIO_config() {
	// P34  准双向
	GPIO_InitTypeDef info;
	info.Mode = GPIO_OUT_PP; // 推挽输出
	info.Pin = GPIO_Pin_4; // 引脚
	GPIO_Inilize(GPIO_P3, &info);
	P34	= 0; // 蜂鸣器默认低电平，防止默认状态下三极管发烫
}
// 初始化
void Buzzer_Init()
{
    GPIO_config();
    EAXSFR();
//	printf("Buzzer_Init\n");
}
static void PWM_config(u16 hz_value) // 为0，停止播放
{
    u16  period = 0; // 周期变量
	PWMx_InitDefine		PWMx_InitStructure;
	if (hz_value != 0)  period =  (MAIN_Fosc / hz_value);
	
	// 配置PWM8
	PWMx_InitStructure.PWM_Mode    		= CCMRn_PWM_MODE1;	//模式,		CCMRn_FREEZE,CCMRn_MATCH_VALID,CCMRn_MATCH_INVALID,CCMRn_ROLLOVER,CCMRn_FORCE_INVALID,CCMRn_FORCE_VALID,CCMRn_PWM_MODE1,CCMRn_PWM_MODE2
	PWMx_InitStructure.PWM_Duty   	 	= 0.5*period;	//PWM占空比时间, 0~Period
	PWMx_InitStructure.PWM_EnoSelect    = hz_value == 0 ? 0 : ENO8P;			//输出通道选择,	ENO1P,ENO1N,ENO2P,ENO2N,ENO3P,ENO3N,ENO4P,ENO4N / ENO5P,ENO6P,ENO7P,ENO8P
	PWM_Configuration(PWM8, &PWMx_InitStructure);			//初始化PWM,  PWMA,PWMB

	// 配置PWMB
	PWMx_InitStructure.PWM_Period   = period - 1;			//周期时间,   0~65535
	PWMx_InitStructure.PWM_DeadTime = 0;					//死区发生器设置, 0~255
	PWMx_InitStructure.PWM_MainOutEnable= ENABLE;			//主输出使能, ENABLE,DISABLE
	PWMx_InitStructure.PWM_CEN_Enable   = ENABLE;			//使能计数器, ENABLE,DISABLE
	PWM_Configuration(PWMB, &PWMx_InitStructure);			//初始化PWM通用寄存器,  PWMA,PWMB

	// 切换PWM通道
	PWM8_SW(PWM8_SW_P34);					//PWM5_SW_P20,PWM5_SW_P17,PWM5_SW_P00,PWM5_SW_P74
	// 初始化PWMB的中断
	NVIC_PWM_Init(PWMB,DISABLE,Priority_0);
}
// 按照指定频率播放
void Buzzer_play(u16 hz_value)
{
    PWM_config(hz_value);
}

static u16 code FREQS[] = {
	523 * 1, 587 * 1, 659 * 1, 698 * 1, 784 * 1, 880 * 1, 988 * 1, 
	523 * 2, 587 * 2, 659 * 2, 698 * 2, 784 * 2, 880 * 2, 988 * 2, 
	523 * 4, 587 * 4, 659 * 4, 698 * 4, 784 * 4, 880 * 4, 988 * 4, 
	523 * 8, 587 * 8, 659 * 8, 698 * 8, 784 * 8, 880 * 8, 988 * 8, 
};
// 按照指定音节播放
void Buzzer_beep(u8 idx)
{
	Buzzer_play(FREQS[idx]);	

}
void Buzzer_alarm(){
	Buzzer_beep(0);
	os_wait2(K_TMO,40);
	Buzzer_play(0);
	os_wait2(K_TMO,20);
	
	Buzzer_beep(1);
	os_wait2(K_TMO,20);
	Buzzer_play(0);
	os_wait2(K_TMO,20);
	
	Buzzer_beep(2);
	os_wait2(K_TMO,40);
	Buzzer_play(0);
	os_wait2(K_TMO,20);
	
	Buzzer_beep(3);
	os_wait2(K_TMO,20);
	Buzzer_play(0);
	os_wait2(K_TMO,20);
	
	Buzzer_beep(4);
	os_wait2(K_TMO,40);
	Buzzer_play(0);
	os_wait2(K_TMO,20);
	
	Buzzer_beep(5);
	os_wait2(K_TMO,20);
	Buzzer_play(0);
	os_wait2(K_TMO,20);
	
	Buzzer_beep(6);
	os_wait2(K_TMO,40);
	Buzzer_play(0);
	os_wait2(K_TMO,20);
}
// 停止播放
void Buzzer_stop()
{
    Buzzer_play(0);
}